package server

import (
	"net/http"
	"smart-weekly-report/config"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// 同步Git提交
func SyncGitCommits(c *gin.Context) {
	gitService := NewGitService(config.AppConfig.GitRepoPath)
	err := gitService.SyncCommits()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Git提交同步完成"})
}

type WeeklyReport struct {
	ID          int
	Week        int
	Content     string
	GeneratedAt time.Time
	Sent        bool
}

// 生成周报
func GenerateWeeklyReport(c *gin.Context) {
	weekStr := c.Query("week")
	var week int
	apiConfig := config.GetConfig()
	if weekStr == "" {
		_, week = time.Now().ISOWeek()
	} else {
		week, _ = strconv.Atoi(weekStr)
	}

	// 获取Git提交
	gitService := NewGitService(apiConfig.GitRepoPath)
	commits, err := gitService.GetCommitsByWeek(week)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	// 通过AI生成周报内容
	genkitService := NewZhipuAIService(apiConfig.ZhipuAPIKey)
	content, err := genkitService.GenerateReportContent(commits)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 保存周报
	report := WeeklyReport{
		Week:        week,
		Content:     content,
		GeneratedAt: time.Now(),
		Sent:        false,
	}

	config.Db.Create(&report)

	c.JSON(http.StatusOK, gin.H{
		"message":   "周报生成完成",
		"week":      week,
		"report_id": report.ID,
	})
}

// 发送周报
func SendReportToFeishu(c *gin.Context) {
	reportID := c.Query("report_id")

	var report WeeklyReport
	result := config.Db.Where("sent = ?", false).First(&report, reportID)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "周报不存在"})
		return
	}
	apiConfig := config.GetConfig()
	feishuService := NewFeishuService(apiConfig.FeishuWebhook, apiConfig.FeishuKey)
	err := feishuService.SendFormattedCard(&report)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	// 更新数据库记录
	report.Sent = true
	config.Db.Save(&report)
	c.JSON(http.StatusOK, gin.H{"message": "周报发送成功"})
}

// 获取周报历史
func GetReportHistory(c *gin.Context) {
	var reports []WeeklyReport
	config.Db.Order("week desc").Find(&reports)

	c.JSON(http.StatusOK, gin.H{"reports": reports})
}
